package com.feng.util;

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by Administrator on 2017/3/10.
 */
public class RedisUtil {
    public static String encodeToString(BufferedImage image, String type) {  //将<span style="font-family: Arial, Helvetica, sans-serif;">BufferedImage 转化为string，type是文件类型：jpg，png等</span>
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }
    /*
     * 读取图片
     */
    public static String readImage(MultipartFile file,String type){  //传入图片名和类型，读取文件并返回string
        //<span style="font-family: Arial, Helvetica, sans-serif;">System.getProperty("user.dir") 是获取当前工程的根目录，target\\classes下是resource的目录，</span>
        try {
            BufferedImage img = ImageIO.read(file.getInputStream());
            BufferedImage newImg;
            String imagestr;
            imagestr = encodeToString(img, type);
            return imagestr;
        }
        catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        }
        catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return null;
    }
}
